package com.zheng.oss.web.util;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by likun on 2018/4/25.
 */
public class FileManager implements FileManagerConfig {
    protected final static Logger _log = LoggerFactory.getLogger(FileManager.class);

    private static final long serialVersionUID = 1L;
    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageServer storageServer;
    private static StorageClient storageClient;

    static {
        try {
            String classPath = new File(FileManager.class.getResource("/").getFile()).getCanonicalPath();

            String fdfsClientConfigFilePath = classPath + File.separator + CLIENT_CONFIG_FILE;
            ClientGlobal.init(fdfsClientConfigFilePath);

            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();

            storageClient = new StorageClient(trackerServer, storageServer);

        } catch (Exception e) {
            _log.error("初始化上传信息失败！" + e);
        }
    }

    /**
     * <strong>方法概要： 文件上传</strong> <br>
     * <strong>创建时间： 2016-9-26 上午10:26:11</strong> <br>
     *
     * @param file
     * @return String[] 0 groupName
     * 1 fileName 2fileAbsolutePath
     * @author Wang Liang
     */
    public static UploadResult upload(MultipartFile file) {
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        FastDFSFile fastDFSFile = null;
        try {
            fastDFSFile = new FastDFSFile(file.getBytes(), ext);
        } catch (IOException e) {
            e.printStackTrace();
        }
        NameValuePair[] meta_list = new NameValuePair[4];
        meta_list[0] = new NameValuePair("fileName", file.getOriginalFilename());
        meta_list[1] = new NameValuePair("fileLength", String.valueOf(file.getSize()));
        meta_list[2] = new NameValuePair("fileExt", ext);
        meta_list[3] = new NameValuePair("fileAuthor", "uploader");
        String[] uploadResults = null;
        try {
            uploadResults = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), meta_list);
        } catch (Exception e) {
            _log.error("上传文件失败！" + e);
            return null;
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];
        String fileAbsolutePath = PROTOCOL
                + TRACKER_NGNIX_ADDR
                //+ trackerServer.getInetSocketAddress().getHostName()
                + ":" + TRACKER_NGNIX_PORT
                + SEPARATOR + groupName
                + SEPARATOR + remoteFileName;
        UploadResult uploadResult = new UploadResult();
        uploadResult.setGroupName(groupName);
        uploadResult.setFileAbsolutePath(fileAbsolutePath);
        uploadResult.setRemoteFileName(remoteFileName);
        return uploadResult;
    }

    /**
     * <strong>方法概要： 文件下载</strong> <br>
     * <strong>创建时间： 2016-9-26 上午10:28:21</strong> <br>
     *
     * @param groupName
     * @param remoteFileName
     * @return returned value comment here
     * @author Wang Liang
     */
    public static ResponseEntity<byte[]> download(String groupName, String remoteFileName, String specFileName) {
        byte[] content = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            content = storageClient.download_file(groupName, remoteFileName);
            headers.setContentDispositionFormData("attachment", new String(specFileName.getBytes("UTF-8"), "iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        } catch (Exception e) {
            _log.error("下载文件失败！" + e);
        }
        return new ResponseEntity<>(content, headers, HttpStatus.CREATED);
    }

    public static boolean delete(String groupName, String remoteFileName) throws Exception {
        int i = 1;
        try {
            i = storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            _log.error("删除文件失败！" + e);
            throw new Exception("删除文件失败");
        }
        return i == 0;
    }
}
